import React, { Component } from 'react'
import TodoItem from './TodoItem'

export default class TodoList extends Component {
  state = {
    type: 'all' // 选项卡状态
  }

  // 点击，设置当前选项卡状态
  handleChange(type, event) {
    event.preventDefault()
    this.setState({
      type
    })
  }

  // 计算当前应该渲染的待办事项
  getCurrentTodos() {
    let currentTodos
    switch(this.state.type) {
      case 'all':
        currentTodos = this.props.todos
        break
      case 'completed':
        currentTodos = this.props.todos.filter(todo => todo.completed)
        break
      case 'uncompleted':
        currentTodos = this.props.todos.filter(todo => !todo.completed)
        break
      default:
        currentTodos = []
    }
    return currentTodos
  }

  render() {
    const { type } = this.state
    const currentTodos = this.getCurrentTodos()
    return (
      <div className="container">
        {/* 选项卡 */}
        <div className="tabs">
          <ul>
            <li className={type === 'all' ? 'is-active' : ''}><a href="/" onClick={this.handleChange.bind(this, 'all')}>所有</a></li>
            <li className={type === 'completed' ? 'is-active' : ''}><a href="/" onClick={this.handleChange.bind(this, 'completed')}>已完成</a></li>
            <li className={type === 'uncompleted' ? 'is-active' : ''}><a href="/" onClick={this.handleChange.bind(this, 'uncompleted')}>未完成</a></li>
          </ul>
        </div>
        {/* 待办事项 */}
        {
          this.props.todos.length
            ?
            (
              <div className="columns is-multiline is-mobile">
                {
                  // 列表渲染
                  currentTodos.map(todo => (
                    <div className="column is-one-quarter" key={todo.id}>
                      {/* 将 todo 对象的各属性传递给 TodoItem 组件实例 */}
                      <TodoItem {...todo} />
                    </div>
                  ))
                }
              </div>
            )
            :
            (
              <div>待办事项列表为空</div>
            )
        }
        
      </div>
    )
  }
}
